import { createHash } from "crypto";
import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
import { extname, join } from "path";
import { getRoot } from "../data/Config";
export const TempPath = join(getRoot(), "tinyTemp");
if (!existsSync(TempPath)) {
    mkdirSync(TempPath);
}

export async function compress(file: string, key: string,callback:Function){
    await compressImage(file,key);
    callback && callback();
}

const tinify = require("tinify");
async function compressImage(file: string, key: string) {
    tinify.key = key;
    let sourceData = readFileSync(file);
    let md5 = createHash('md5');
    md5.update(sourceData);
    let md5Str = md5.digest('hex');
    return new Promise((resolve, reject) => {
        let fileType = extname(file);
        let tempFilePath = join(TempPath, md5Str) + fileType;
        if (existsSync(tempFilePath)) {
            copyFileSync(tempFilePath, file);
            resolve();
        } else {
            tinify.fromBuffer(sourceData).toBuffer(function (err, resultData) {
                if (err) reject(err);
                writeFileSync(tempFilePath,resultData);
                copyFileSync(tempFilePath, file);
                resolve();
            });
        }
    })
}